//
//  BiContrCheckViewController.m
//  TrunkIndustryManageSystem
//
//  Created by 李璐西 on 15-4-22.
//  Copyright (c) 2015年 李璐西. All rights reserved.
//

#import "BiContrCheckViewController.h"

@interface BiContrCheckViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate>{
    
    __weak IBOutlet UIScrollView *_ScrollView;

    NSInteger countIm;  //图片需上传计数
    NSInteger countUp; //图片上传完成计数
    
    NSMutableArray * _netImBtnArr; //网路图片按钮
    
    NSMutableArray * _locImBtnArr; //本地拍摄照片按钮
    
    NSMutableArray * _netImageObArr;
    
    BOOL isSave;
    
    NSInteger _index;  //纪录删除图片的索引

}
@property (weak, nonatomic) IBOutlet UILabel *labVINTip;
@property (weak, nonatomic) IBOutlet UILabel *labCarTypeTip;
@property (weak, nonatomic) IBOutlet UITextView *textvRequir;
@property (weak, nonatomic) IBOutlet UILabel *labVip;
@property (weak, nonatomic) IBOutlet UILabel *labType;
@property (weak, nonatomic) IBOutlet UILabel *labVin;
@property (weak, nonatomic) IBOutlet UILabel *labBrand;
@property (weak, nonatomic) IBOutlet UILabel *labCartype;
@property (weak, nonatomic) IBOutlet UILabel *labCarSeries;
@property (weak, nonatomic) IBOutlet UILabel *labGiveMoney;
@property (weak, nonatomic) IBOutlet UILabel *labSaleMoney;
@property (weak, nonatomic) IBOutlet UILabel *labGiveDetail;

@property (weak, nonatomic) IBOutlet UILabel *labSaler;
@property (weak, nonatomic) IBOutlet UILabel *labReserveTime;
@property (weak, nonatomic) IBOutlet UILabel *labMakeDocTime;
@property (weak, nonatomic) IBOutlet UILabel *labHandOverTime;
@property (weak, nonatomic) IBOutlet UILabel *labDownPayment;
@property (weak, nonatomic) IBOutlet UIButton *btnTakePhoto;



@end

@implementation BiContrCheckViewController
- (id)init{

    self = [super init];
    
    if (self) {
        
        isSave = NO;
        _netImBtnArr = [NSMutableArray new];
        
        _locImBtnArr = [NSMutableArray new];
        
        _netImageObArr = [NSMutableArray new];
        
        countIm = 0;
        countUp = 0;

    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setNavBackBtn];
    [self setNavBarTitle:@"整车销售合同完结上传"];
    [self setNavBarWithHidden:NO];
    [self addTestView];
    _ScrollView.contentSize = CGSizeMake(320, 600);
    self.textvRequir.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    self.textvRequir.layer.borderWidth = 0.5;
    
    [self dataFll];
    
}

- (void)dataFll{

    self.labVip.text = self.Centity.member_name;
    
    self.labVin.text = self.Centity.car_vin;
    
    self.labBrand.text = self.Centity.car_brand;
    
    self.labCarSeries.text = self.Centity.car_carSeries;
    
    self.labCartype.text = self.Centity.car_carCategoryName;
    
    self.labSaler.text = self.Centity.saleman_name;
    
    self.labReserveTime.text = self.Centity.carOrder_orderTime;
    
    self.labMakeDocTime.text = self.Centity.carOrder_createTime;
    
    self.labHandOverTime.text = self.Centity.carOrder_connectCarTime;
    
    self.labSaleMoney.text = [NSString stringWithFormat:@"%@元",self.Centity.carOrder_sellPrice];
    
    self.labGiveDetail.text = self.Centity.carOrder_giftDetail;
    
    _textvRequir.text = self.Centity.carOrder_specialDemand;
    
    self.labGiveMoney.text = [NSString stringWithFormat:@"%@元",self.Centity.carOrder_giftMoney];
    self.labDownPayment.text = [NSString stringWithFormat:@"%@元",self.Centity.carOrder_subscription];
    
    if (self.Centity.carOrder_orderType.hash == @"1".hash) {
        
        self.labType.text = @"订单车";
        
        [self setVinCarTypeHiden:YES];
    }else  if (self.Centity.carOrder_orderType.hash == @"2".hash) {
        
        [self setVinCarTypeHiden:NO];
        
        self.labType.text = @"现车";
    }
    
    [_netImageObArr addObjectsFromArray:self.Centity.carOrder_ConnectImgArr];
    
    for (int i = 0; i < self.Centity.carOrder_ConnectImgArr.count; i++) {
        
        UIButton * imageViewtbn = [[UIButton alloc] initWithFrame:CGRectMake(5*(i+1)+i*(MAIN_SCREEN_WIDTH-20)/3, self.btnTakePhoto.frame.origin.y + self.btnTakePhoto.frame.size.height + 5, (MAIN_SCREEN_WIDTH-20)/3, (MAIN_SCREEN_WIDTH-20)/3)];
        [imageViewtbn addTarget:self action:@selector(btnImageClcik:) forControlEvents:UIControlEventTouchUpInside];
        imageViewtbn.tag = 100+i;
        
        [_netImBtnArr addObject:imageViewtbn];
        
        [imageViewtbn reloadImage:self.Centity.carOrder_ConnectImgArr[i]];
        
        [_ScrollView addSubview:imageViewtbn];
        
        if (0 == i) {
            
            
            _ScrollView.frame = CGRectMake(0,_ScrollView.frame.origin.y, _ScrollView.frame.size.width, _ScrollView.frame.size.height + imageViewtbn.frame.size.height + 10);
            
            _ScrollView.contentSize = CGSizeMake(_ScrollView.frame.size.width, 825);
        }
    }
    
}

- (void)setVinCarTypeHiden:(BOOL)isHiden{

    self.labCartype.hidden = isHiden;
    self.labCarTypeTip.hidden = isHiden;
    self.labVin.hidden = isHiden;
    self.labVINTip.hidden = isHiden;
}


- (IBAction)btnCameroClick:(UIButton *)sender {
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"相机功能不可用" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:picker animated:YES completion:nil];
    
}

- (IBAction)btnSaveCheckClick:(UIButton *)sender {
    
    if (1 == sender.tag) {
        
        NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:self.Centity.carOrder_id,@"id",@"0",@"status", nil];
        
        [[BiNetEngine shareInstance] requestSaleContractAssocCheck:self paraDict:paraDic];
        
    }else if (0 == sender.tag){
        
        

    }
    
    
    for (int i = 0; i<_locImBtnArr.count; i++) {
        
        UIImage * image = [_locImBtnArr[i] currentBackgroundImage];
        
        NSString * filename = [NSString stringWithFormat:@"%u",arc4random()+i];
        
        NSDictionary * paraDicIm1 = [NSDictionary dictionaryWithObjectsAndKeys:self.Centity.carOrder_id,@"id",@"1",@"imgType",filename,@"fileName", nil];
        
        [[BiNetEngine shareInstance] requestSaleContractImageRCHY:self withImge:image paraDic:paraDicIm1];
        
    }
    
    [self asyshowHUDView:WAITING CurrentView:self];
}


#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSInteger Count = _netImBtnArr.count + _locImBtnArr.count;
    
    if (Count == 3) {
        
        [self showMessage:@"亲，最多三张图片！"];
        
        return;
    }
    
    image = [BiUtil scaleToSize:image size:CGSizeMake(240, 200)];
    
    UIButton * imageViewtbn = [[UIButton alloc] initWithFrame:CGRectMake(5*(Count+1)+Count*(MAIN_SCREEN_WIDTH-20)/3, self.btnTakePhoto.frame.origin.y + self.btnTakePhoto.frame.size.height + 5, (MAIN_SCREEN_WIDTH-20)/3, (MAIN_SCREEN_WIDTH-20)/3)];

    [_ScrollView addSubview:imageViewtbn];
    
    [imageViewtbn addTarget:self action:@selector(btnImageClcik:) forControlEvents:UIControlEventTouchUpInside];
    
    imageViewtbn.tag = 200+Count;
    
    [imageViewtbn setBackgroundImage:image forState:UIControlStateNormal];
    
    if (Count == 0) {
        
        _ScrollView.frame = CGRectMake(_ScrollView.frame.origin.x, _ScrollView.frame.origin.y, _ScrollView.frame.size.width, _ScrollView.frame.size.height + imageViewtbn.frame.size.height + 20);
        
        _ScrollView.contentSize = CGSizeMake(_ScrollView.frame.size.width, 825);
        
        
    }
    [_locImBtnArr addObject:imageViewtbn];
    
    countIm ++;
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)btnImageClcik:(UIButton *)button{
    
    UIActionSheet* mySheet = [[UIActionSheet alloc]
                              initWithTitle:nil
                              delegate:self
                              cancelButtonTitle:@"取消"
                              destructiveButtonTitle:@"删除图片"
                              otherButtonTitles:@"查看大图", nil];
    [mySheet showInView:self.view];
    
    mySheet.tag = button.tag;
    
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSInteger index = actionSheet.tag%100;
    
    _index = index;
    
    switch (buttonIndex)
    {
        case 0:
        {  //删除图片
            
            if (actionSheet.tag < 200) { //网络图片
                
                NSDictionary * deleDic =[NSDictionary dictionaryWithObjectsAndKeys:self.Centity.carOrder_id,@"id",[_netImageObArr[index] lastPathComponent],@"filePath",@"1",@"imgType", nil];
                
                [_netImageObArr removeObjectAtIndex:index];
                
                [[BiNetEngine shareInstance] requestSaleContractImageDel:self paraDic:deleDic];
                
                [self asyshowHUDView:WAITING CurrentView:self];
                
            }else{//本地拍照
                
                NSInteger  indexLoc = index - _netImBtnArr.count;
                
                UIButton * nowbutn = _locImBtnArr[indexLoc];
                
                [nowbutn removeFromSuperview];
                
                [_locImBtnArr removeObjectAtIndex:indexLoc];
                
                for (int i = indexLoc; i< _locImBtnArr.count;i++) {
                    
                    UIButton * butn = _locImBtnArr[i];
                    
                    butn.tag --;
                    
                    butn.frame = CGRectMake(butn.frame.origin.x-butn.frame.size.width-5, butn.frame.origin.y, butn.frame.size.width, butn.frame.size.height);
                }
            }
            
        }
            break;
        case 1:
        {  // 查看大图
            
            if (actionSheet.tag < 200) { //网络图片
                
                [BiUtil pusuToImageVc:self image:[_netImBtnArr[index] currentBackgroundImage] title:@"合同照片"];
            }else{//本地拍照
            
                [BiUtil pusuToImageVc:self image:[_locImBtnArr[(index-_netImBtnArr.count)] currentBackgroundImage] title:@"合同照片"];
            }
            
        }
            break;
        default:
            break;
    }
}


#pragma mark -textview delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if ([@"\n" isEqualToString:text] == YES)
    {
        [textView resignFirstResponder];
        
        
        return NO;
    }
    return YES;
}

#pragma -mark Net Delegate
- (void)onNetEngineResponse:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    
    NSDictionary * entity_ = (NSDictionary *)entity;
    
    [self showMessage:entity_[@"result_info"]];
    
    if ([entity_[@"response_status"] integerValue] != 200) {
        
         [self removeHUDView:self];
        
        return;
        
    }
    
    switch (tag) {
        case NET_GET_XINGXIAO_CONTRACT_CHECK:
            isSave = YES;

            break;
        case NET_GET_XINGXIAO_CONTRACT_UPIMAGERCHY:
        {

            countUp++;
        }
            break;
        case NET_GET_XINGXIAO_CONTRACT_DEL_IMAGE:
        {
        
            UIButton * nowbtn = _netImBtnArr[_index];
            
            [nowbtn removeFromSuperview];
            
            [_netImBtnArr removeObjectAtIndex:_index];
            
            
            for (int i = _index; i< _netImBtnArr.count;i++) {
                
                UIButton * butn = _netImBtnArr[i];
                
                butn.tag --;
                
                butn.frame = CGRectMake(butn.frame.origin.x-butn.frame.size.width-5, butn.frame.origin.y, butn.frame.size.width, butn.frame.size.height);
            }
            
            for (int i = 0; i< _locImBtnArr.count;i++) {
                
                UIButton * butn = _locImBtnArr[i];
                
                butn.tag --;
                
                butn.frame = CGRectMake(butn.frame.origin.x-butn.frame.size.width-5, butn.frame.origin.y, butn.frame.size.width, butn.frame.size.height);
            }
            
            [self removeHUDView:self];
        }
            
            break;
        default:
            break;
    }
 
    if ((countUp == countIm) && isSave) {
        
        [self removeHUDView:self];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)onNetEngineResponseFail:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    [self removeHUDView:self];
}


@end
